import pytest
import allure
from playwright.sync_api import Page, sync_playwright
from datetime import datetime
import os
import json

# 截图保存目录
SCREENSHOTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "screenshots")
# 确保目录存在
os.makedirs(SCREENSHOTS_DIR, exist_ok=True)

def take_screenshot(page: Page, name: str):
    """截图并保存，返回文件路径"""
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    filename = f"{name}_{timestamp}.png"
    filepath = os.path.join(SCREENSHOTS_DIR, filename)
    page.screenshot(path=filepath)
    return filepath

@pytest.fixture(scope="function")
def page(browser, request):
    """创建页面并设置视口大小"""
    page = browser.new_page(
        viewport={"width": 1920, "height": 1080},
        record_video_dir=os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "videos") if os.getenv("RECORD_VIDEO") else None
    )
    yield page
    
    # 捕获测试失败的截图
    if hasattr(request, 'node') and hasattr(request.node, 'result') and request.node.result.outcome == 'failed':
        screenshot_path = take_screenshot(page, f"failed_{request.node.name}")
        allure.attach.file(screenshot_path, name="失败截图", attachment_type=allure.attachment_type.PNG)
        
        # 捕获页面的HTML
        html_content = page.content()
        allure.attach(html_content, name="页面HTML", attachment_type=allure.attachment_type.HTML)
    
    # 关闭页面
    page.close()

@pytest.fixture(scope="function")
def login(page: Page):
    """登录fixture"""
    with allure.step("执行登录"):
        page.goto("http://localhost:8080")
        
        allure.attach(
            json.dumps({
                "url": "http://localhost:8080",
                "username": "suyuxi",
                "password": "Aa123456"
            }, ensure_ascii=False, indent=2),
            name="登录信息",
            attachment_type=allure.attachment_type.JSON
        )
        
        page.locator('input[placeholder="请输入用户名"]').fill("suyuxi")
        page.locator('input[placeholder="请输入密码"]').fill("Aa123456")
        
        # 截取登录前的页面
        screenshot_path = take_screenshot(page, "login_before")
        allure.attach.file(screenshot_path, name="登录前", attachment_type=allure.attachment_type.PNG)
        
        page.get_by_role("button", name="登录").click()
        page.wait_for_url("**/testplanform/home")
        
        # 截取登录后的页面
        screenshot_path = take_screenshot(page, "login_after")
        allure.attach.file(screenshot_path, name="登录后", attachment_type=allure.attachment_type.PNG)
    
    return page

# 在每个测试执行后处理轨迹
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    result = outcome.get_result()
    
    # 测试用例名称
    test_name = item.name
    
    # 保存结果到测试用例
    setattr(item, "result", result)
    
    # 添加Allure步骤
    if call.when == "call" and result.outcome == "failed":
        # 添加失败原因
        allure.attach(
            str(call.excinfo.value),
            name="异常信息",
            attachment_type=allure.attachment_type.TEXT
        )
        
        # 添加轨迹路径（如果有）
        if hasattr(item, "_trace_path") and item._trace_path:
            allure.attach.file(
                item._trace_path,
                name="播放轨迹",
                attachment_type=allure.attachment_type.ZIP
            ) 